"use strict";
define(["commonUI","getTime", "echarts", "pieChars","template","global"], function (
    commonUI, getTime, echarts, pieChars,template,global
) {
    var projectIdMapOrder = new Map();
    /**
     * 初始化项目列表函数
     */
    function initProjectList(){
        let i = 0;
        global.get("/web/project/listByUser",function(response){
            response.data.projects.forEach(function(project){
                projectIdMapOrder.set(project.id, i++)
            })
        },null,null,false)
        global.get("/web/project/list",function(response){
            var projects = response.data.projects;
            $(".project-list").empty()
            projects.forEach(function(project){
                var _li = '<li class="projectLi" style="cursor:pointer" pid="'+project.id+'"><div class="clearfix"><span class="name pull-left">'+project.name+'</span><span class="num pull-right">'+project.area+'</span></div><div class="clearfix"><span class="location pull-left"><span class="label-text">地点：</span>'+project.city+'</span><span class="unit pull-right">建筑面积</span></div></li>';
                $(".project-list").append(_li);
            })
        },null,null,false)
    }
    /**
     * 初始化项目列表上方的三个数据
     */
    function initDataAboveProjectList(){
        global.get("/web/index/projectListAboveData",function(response){
            var data = response.data;
            data.totalEnergyArea=parseFloat(data.totalEnergyArea).toFixed(0);
            var html = `
            <div class="info-content">
                <div class="info-wrap">
                    <img src="/images/123_13.png">
                    <div class="detail">
                    <div class="label-top">总供能面积</div>
                        <div class="num text-overflow">{{data.totalEnergyArea}}<span class="unit">万平方米</span></div>
                    </div>
                </div> 
                <div class="info-wrap" style="width: 155px;">
                    <img src="/images/123_15.png">
                    <div class="detail">
                        <div class="label-top">地源热泵装机容量</div>
                        <div class="num text-overflow">{{data.heatPumpCapacity}}<span class="unit">千瓦</span></div>
                    </div>
                </div>
                <div class="info-wrap" style="width: 120px;">
                    <img src="/images/123_17.png">
                    <div class="detail">
                        <div class="label-top">设备数量</div>
                        <div class="num text-overflow">{{data.equipmentCount}}<span class="unit">台</span></div>
                    </div>
                 </div>
            </div>
            `
            var tplHtml = template.compile(html);
            $("#div1").html(tplHtml({
                "data": data
            }));
        });
    }

    /**
     * 初始化下方的六个数字的函数
     */
    function initNum() {
        global.get("/web/index/bottomData",function(response){
            var data = response.data
            var coalSaved = data.coalSaved.toFixed(2);
            var carbinEmission = data.carbinEmission.toFixed(2);
            var renewEnergy = data.renewEnergy.toFixed(2);
            var providedEnergy = data.providedEnergy.toFixed(2);
            var powercost = data.powercost.toFixed(2);
            var energySavingRate = data.energySavingRate.toFixed(4)*100;
            //可再生能源利用量
            renewEnergy = global.scientificNotation(renewEnergy);
            coalSaved = global.scientificNotation(coalSaved);
            carbinEmission = global.scientificNotation(carbinEmission);
            providedEnergy = global.scientificNotation(providedEnergy);
            powercost = global.scientificNotation(powercost);
            energySavingRate = parseFloat(energySavingRate).toFixed(2);
            renewEnergy.a = parseFloat(renewEnergy.a).toFixed(1);
            coalSaved.a = parseFloat(coalSaved.a).toFixed(1);
            carbinEmission.a = parseFloat(carbinEmission.a).toFixed(1);
            providedEnergy.a = parseFloat(providedEnergy.a).toFixed(1);
            powercost.a = parseFloat(powercost.a).toFixed(1);
            var html = `
            <div class="info-wrap">
                <div class="title-text">可再生能源利用量</div>
                <div class="num-text">{{renewEnergy.a}}*10<span class="top-num">{{renewEnergy.b}}</span><span class="unit">kJ</span></div>
            </div>
            <div class="info-wrap">
                <div class="title-text">节能量</div>
                <div class="num-text">{{coalSaved.a}}*10<span class="top-num">{{coalSaved.b}}</span><span class="unit">吨标煤</span></div>
            </div>
            <div class="info-wrap">
                <div class="title-text">碳减排量</div>
                <div class="num-text">{{carbinEmission.a}}*10<span class="top-num">{{carbinEmission.b}}</span><span class="unit">吨</span></div>
            </div>
            <div class="info-wrap">
                <div class="title-text">供能（冷、热）量</div>
                <div class="num-text">{{providedEnergy.a}}*10<span class="top-num">{{providedEnergy.b}}</span><span class="unit">kJ</span></div>
            </div>
            <div class="info-wrap">
                <div class="title-text">耗电量</div>
                <div class="num-text">{{powercost.a}}*10<span class="top-num">{{powercost.b}}</span><span class="unit">吨标煤</span></div>
            </div>
            <div class="info-wrap">
                <div class="title-text">节能率</div>
                <div class="num-text">{{energySavingRate}}%</div>
            </div>
            `
            var tplHtml = template.compile(html);
            $(".center-wrap").html(tplHtml({
                "renewEnergy": renewEnergy,
                "coalSaved":coalSaved,
                "carbinEmission": carbinEmission,
                "providedEnergy":providedEnergy,
                "powercost":powercost,
                "energySavingRate":energySavingRate
            }));
        })
    }

    var chart2, chart3;
    var app = {
        init: function () {
            this.eventBind();
            // getTime.resize();
            getTime.getNowDate();
            getTime.getTimeInfo();
            initDataAboveProjectList();
            initProjectList();
            initNum();
            this.initScroll();
            this.initChart1();
            this.initChart2(); //默认显示供冷模式
            this.initChart3(1); //默认显示供冷模式
        },
        initScroll: function () {
            $(".project-content").jqListScroll({
                rowHeight: 76,
                speed: 3000,
                type: 2,
                isMouse: true
            });
        },
        initChart1: function () {
            var xAxis = [], option = [];
            global.get("/web/index/systemPowercost",function(response){
                if(response.success){
                    var types= response.data.types;
                    var datas = response.data.powercosts
                    for(var i=0;i<response.data.types.length;i++){
                        xAxis.push(types[i]);
                        option.push({
                            "name":types[i],
                            "value":datas[i]!=null?Math.floor(parseFloat(datas[i])):0
                        });
                    }
                    $("#chart1").pieChars({
                        "data": option,
                        "name": "KWH",
                        "subName": "耗能总量",
                    });
                }else{
                    alert(response.message);
                }
            })
            
        },
        initChart2: function () {
            if (chart2) {
                chart2.dispose();
            }
            var xArr = [], yArr = [];
            global.get("/web/index/statisticsPowercostByMode",function(response){
                if(response.success){
                    var dates= response.data.dates;
                    var datas = response.data.powercosts
                    var modeName = response.data.modeName;
                    for(var i=0;i<response.data.dates.length;i++){
                        xArr.push(dates[i].substr(8,2) + "日");
                        yArr.push(datas[i].toFixed(3));
                    }
                    var option = {
                        tooltip: {
                            trigger: "axis",
                            axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                                type: "shadow"        // 默认为直线，可选为：'line' | 'shadow'
                            },
                            formatter: "{b} <br/>"+"能耗"+": {c}"
                        },
                        grid: {
                            left: 20,
                            right: 20,
                            bottom: 0,
                            top: 30,
                            containLabel: true
                        },
                        xAxis: [
                            {
                                type: "category",
                                axisTick: {
                                    show: false
                                },
                                axisLine: {
                                    lineStyle: {
                                        color: "#8cbdd2",
                                        opacity: 0.2
                                    }
                                },
                                axisLabel: {
                                    color: "#8cbdd2"
                                },
                                data: xArr
                            }
                        ],
                        yAxis: [
                            {
                                name:"KWH",
                                type: "value",
                                splitNumber: 4,
                                axisTick: {
                                    show: false
                                },
                                axisLine: {
                                    lineStyle: {
                                        color: "#8cbdd2",
                                        opacity: 0.2
                                    }
                                },
                                axisLabel: {
                                    color: "#8cbdd2"
                                },
                                splitLine: {
                                    lineStyle: {
                                        color: "#8cbdd2",
                                        opacity: 0.2
                                    }
                                }
                            }
                        ],
                        series: [
                            {
                                name: "KWH",
                                type: "bar",
                                barWidth: 16,
                                data: yArr
                            }
                        ],
                        color: ["#ffcd33"]
                    };
                    chart2 = echarts.init(document.getElementById("chart2"));
                    chart2.setOption(option);
                }else{
                    alert(response.message);
                }
            })
            // global.get("/web/index/statisticsPowercostByMode?mode="+mode,function(response){
            //     if(response.success){
            //         var dates= response.data.dates;
            //         var datas = response.data.powercosts
            //         for(var i=0;i<response.data.dates.length;i++){
            //             xArr.push(dates[i].substr(8,2) + "日");
            //             yArr.push(datas[i].toFixed(3));
            //         }
            //         var option = {
            //             tooltip: {
            //                 trigger: "axis",
            //                 axisPointer: {            // 坐标轴指示器，坐标轴触发有效
            //                     type: "shadow"        // 默认为直线，可选为：'line' | 'shadow'
            //                 },
            //                 formatter: "{b} <br/>"+typeName+": {c}"
            //             },
            //             grid: {
            //                 left: 20,
            //                 right: 20,
            //                 bottom: 0,
            //                 top: 30,
            //                 containLabel: true
            //             },
            //             xAxis: [
            //                 {
            //                     type: "category",
            //                     axisTick: {
            //                         show: false
            //                     },
            //                     axisLine: {
            //                         lineStyle: {
            //                             color: "#8cbdd2",
            //                             opacity: 0.2
            //                         }
            //                     },
            //                     axisLabel: {
            //                         color: "#8cbdd2"
            //                     },
            //                     data: xArr
            //                 }
            //             ],
            //             yAxis: [
            //                 {
            //                     name:"KWH",
            //                     type: "value",
            //                     splitNumber: 4,
            //                     axisTick: {
            //                         show: false
            //                     },
            //                     axisLine: {
            //                         lineStyle: {
            //                             color: "#8cbdd2",
            //                             opacity: 0.2
            //                         }
            //                     },
            //                     axisLabel: {
            //                         color: "#8cbdd2"
            //                     },
            //                     splitLine: {
            //                         lineStyle: {
            //                             color: "#8cbdd2",
            //                             opacity: 0.2
            //                         }
            //                     }
            //                 }
            //             ],
            //             series: [
            //                 {
            //                     name: "KWH",
            //                     type: "bar",
            //                     barWidth: 16,
            //                     data: yArr
            //                 }
            //             ],
            //             color: ["#ffcd33"]
            //         };
            //         chart2 = echarts.init(document.getElementById("chart2"));
            //         chart2.setOption(option);
            //     }else{
            //         alert(response.message);
            //     }
            // })
        },
        initChart3: function (type) {
            if (chart3) {
                chart3.dispose();
            }
            var typeName = "";
            var mode = 0;
            var color = null;
            if(type==1) {
                typeName = "供冷";
                mode = 0;
                color = "#8cbdd2";
            }else {
                typeName = "供暖";
                mode = 1;
                
            }
            var xArr = [], yArr = [];
            global.get("/web/index/globalSystemEfficiency?mode="+mode,function(response){
                if(response.success){
                    var dates= response.data.dates;
                    var datas = response.data.systemEfficiency;
                    for(var i=0;i<response.data.dates.length;i++){
                        xArr.push(dates[i].substr(8,2) + "日");
                        yArr.push(datas[i].toFixed(3));
                    }
                    var option = {
                        tooltip: {
                            trigger: "axis",
                            formatter: "{b} <br/>"+typeName+": {c}"
                        },
                        grid: {
                            left: 20,
                            right: 20,
                            bottom: 0,
                            top: 10,
                            containLabel: true
                        },
                        xAxis: [
                            {
                                type: "category",
                                boundaryGap: false,
                                axisTick: {
                                    show: false
                                },
                                axisLine: {
                                    lineStyle: {
                                        color: "#8cbdd2",
                                        opacity: 0.2
                                    }
                                },
                                axisLabel: {
                                    color: "#8cbdd2"
                                },
                                splitLine: {
                                    show: true,
                                    lineStyle: {
                                        color: "#8cbdd2",
                                        opacity: 0.2
                                    }
                                },
                                data: xArr
                            }
                        ],
                        yAxis: [
                            {
                                type: "value",
                                splitNumber: 4,
                                axisTick: {
                                    show: false
                                },
                                axisLine: {
                                    lineStyle: {
                                        color: "#8cbdd2",
                                        opacity: 0.2
                                    }
                                },
                                axisLabel: {
                                    color: "#8cbdd2"
                                },
                                splitLine: {
                                    lineStyle: {
                                        color: "#8cbdd2",
                                        opacity: 0.2
                                    }
                                }
                            }
                        ],
                        series: [
                            {
                                name: "统计",
                                type: "line",
                                smooth: true,
                                areaStyle: {
                                    normal: {
                                        // opacity: 0.2
                                        color: {
                                            type: 'linear',
                                            x: 0,
                                            y: 0,
                                            x2: 0,
                                            y2: 1,
                                            colorStops: mode===0?[{
                                                offset: 0, color: 'rgba(99,237,248,0.8)' // 0% 处的颜色
                                            }, {
                                                offset: 1, color: 'rgba(99,237,248,0)' // 100% 处的颜色
                                            }]:[{
                                                offset: 0, color: 'rgba(223,93,96,0.8)' // 0% 处的颜色
                                            }, {
                                                offset: 1, color: 'rgba(223,93,96,0)' // 100% 处的颜色
                                            }],
                                            globalCoord: false // 缺省为 false
                                        }
                                    }
                                },
                                data: yArr
                            }
                        ],
                        color: mode===0?["#63edf8"]:["#df5d60"]
                    };
                    chart3 = echarts.init(document.getElementById("chart3"));
                    chart3.setOption(option);


                }else{
                    alert(response.message);
                }
            })
        },

        /** 事件绑定 */
        eventBind: function () {
            $(document).on("click", ".header", function () {
                window.open("/system/main.html","_self");
            })
            // $(document).on("click", "#chartLabel2 li", function () {
            //     $(this).addClass("active").siblings("li").removeClass("active");
            //     var type = $(this).attr("type");
            //     app.initChart2(type);
            // })
            $(document).on("click", "#chartLabel3 li", function () {
                $(this).addClass("active").siblings("li").removeClass("active");
                var type = $(this).attr("type");
                app.initChart3(type);
            })
            // 全屏
            $(document).on('click', "#fullScreen", function() {
                var docElm = document.documentElement;

                if ($('#fullScreen .full-icon').hasClass('expand')) { //进入全屏
                    // var requestMethod = targetDom.requestFullscreen || targetDom.webkitRequestFullScreen;
                    // requestMethod.call(targetDom);
                    if(docElm.requestFullscreen) {
                        docElm.requestFullscreen();
                    } else if (docElm.msRequestFullscreen) {
                        docElm.msRequestFullscreen();
                    } else if(docElm.mozRequestFullscreen) {
                        docElm.mozRequestFullscreen();
                    } else if(docElm.webkitRequestFullscreen) {
                        docElm.webkitRequestFullscreen();
                    }
                    $('#fullScreen .full-icon').removeClass('expand').addClass('compress');
                    $('#fullScreen span').text('退出全屏');
                } else { //退出全屏
                    if (document.exitFullscreen) {
                        document.exitFullscreen();
                    } else if (document.msExitFullscreen) {
                        document.msExitFullscreen();　　
                    } else if (document.mozCancelFullScreen) {
                        document.mozCancelFullScreen();　　
                    } else if (document.webkitExitFullscreen) {
                        document.webkitExitFullscreen();　　
                    }
                    $('#fullScreen .full-icon').removeClass('compress').addClass('expand');
                    $('#fullScreen span').text('全屏展示');
                }
            });
            //esc退出 调整图标样式
            $(window).resize(function() {
                // getTime.resize();
                //判断页面是否全屏
                function checkFull() {
                    var isFull = document.isFullScreen || document.mozIsFullScreen || document.webkitIsFullScreen
                    if (isFull === undefined) isFull = false;
                    return isFull;
                }

                if (!checkFull()) {
                    $('#fullScreen .full-icon').removeClass('compress').addClass('expand');
                    $('#fullScreen span').text('全屏展示');
                }
            })
            $(document).on('click', ".projectLi", function() {
                let pid = $(this).attr("pid")
                global.get("/web/project/"+pid,function (response) {
                    var project = response.data.project;
                    project.index = projectIdMapOrder.get(parseInt(pid))
                    localStorage.setItem("project",JSON.stringify(project));
                    localStorage.setItem("pid",project.index)
                    localStorage.setItem("id",0);
                    localStorage.setItem("cid",-1)
                    location.href = "/system/main.html";
                    
                })
            })
        },
        
    };
    return app;
});